package cn.javase.concurrent._并发编程._04_共享模型之管程._wait与notify;

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class _使用wait与notify的正确姿势 {

    private static final Object room = new Object();      // 房间
    private static boolean hasCigarette = false;          // 烟
    private static boolean hasTakeout = false;            // 外卖

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                while (true) {
                    log.debug("有烟没？ {}", hasCigarette);
                    if (!hasCigarette) {
                        try {
                            log.debug("没有烟，先歇一会~");
                            room.wait(5000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        log.debug("有烟啦，开始干活！！");
                        break;
                    }
                }
            }
        }, "小南").start();
        new Thread(() -> {
            synchronized (room) {
                while (true) {
                    log.debug("外卖到了没？ {}", hasTakeout);
                    if (!hasTakeout) {
                        try {
                            log.debug("没有外卖，先歇一会~");
                            room.wait(5000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        log.debug("有外卖啦，开始吃饭！！");
                        break;
                    }
                }
            }
        }, "小美").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            synchronized (room) {
                log.debug("外卖到啦...");
                hasTakeout = true;
                room.notifyAll();
            }
        }, "外卖员").start();
        new Thread(() -> {
            synchronized (room) {
                log.debug("雪茄到啦...");
                hasCigarette = true;
                room.notifyAll();
            }
        }, "递烟员").start();
    }

}
